package com.bihua.web.controller.iot;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.bihua.common.annotation.Log;
import com.bihua.common.annotation.RepeatSubmit;
import com.bihua.common.core.controller.BaseController;
import com.bihua.common.core.domain.PageQuery;
import com.bihua.common.core.domain.R;
import com.bihua.common.core.page.TableDataInfo;
import com.bihua.common.core.validate.AddGroup;
import com.bihua.common.core.validate.EditGroup;
import com.bihua.common.enums.BusinessType;
import com.bihua.common.utils.StringUtils;
import com.bihua.common.utils.poi.ExcelUtil;
import com.bihua.iot.domain.bo.DeviceCommandsBo;
import com.bihua.iot.domain.vo.DeviceCommandsVo;
import com.bihua.iot.enums.DeviceCommandStatus;
import com.bihua.iot.service.IDeviceCommandsService;
import com.bihua.iot.service.MqttService;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;

/**
 * 设备动作
 *
 * @author bihua
 * @date 2023-07-23
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/iot/devicecommands")
public class DeviceCommandsController extends BaseController {

    private final IDeviceCommandsService iDeviceCommandsService;
    private final MqttService mqttService;
    /**
     * 查询设备动作列表
     */
    @SaCheckPermission("iot:devicecommands:list")
    @GetMapping("/list")
    public TableDataInfo<DeviceCommandsVo> list(DeviceCommandsBo bo, PageQuery pageQuery) {
        return iDeviceCommandsService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出设备动作列表
     */
    @SaCheckPermission("iot:devicecommands:export")
    @Log(title = "设备命令导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DeviceCommandsBo bo, HttpServletResponse response) {
        List<DeviceCommandsVo> list = iDeviceCommandsService.queryList(bo);
        ExcelUtil.exportExcel(list, "设备动作", DeviceCommandsVo.class, response);
    }

    /**
     * 获取设备动作详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("iot:devicecommands:query")
    @GetMapping("/{id}")
    public R<DeviceCommandsVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iDeviceCommandsService.queryById(id));
    }

    /**
     * 新增设备动作
     */
    @SaCheckPermission("iot:devicecommands:add")
    @Log(title = "设备命令新增", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DeviceCommandsBo bo) {
        return toAjax(iDeviceCommandsService.insertByBo(bo));
    }

    /**
     * 修改设备动作
     */
    @SaCheckPermission("iot:devicecommands:edit")
    @Log(title = "设备命令更新", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DeviceCommandsBo bo) {
        return toAjax(iDeviceCommandsService.updateByBo(bo));
    }

    /**
     * 删除设备动作
     *
     * @param ids 主键串
     */
    @SaCheckPermission("iot:devicecommands:remove")
    @Log(title = "设备命令删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iDeviceCommandsService.deleteWithValidByIds(Arrays.asList(ids), true));
    }


    /**
     * 下发设备动作数据
     *
     * @param params 主键串
     */
    @SaCheckPermission("iot:devicecommands:distribute")
    @Log(title = "设备命令下发", businessType = BusinessType.OTHER)
    @PostMapping("/distributeCommand")
    public R<Void> distributeCommand(@RequestBody Map<String, Object> params) {
        Object id = params.get("id");
        if(ObjectUtil.isEmpty(id)){
            return R.fail("参数有误，请核查！");
        }
        long commandId = Long.valueOf(String.valueOf(id));
        DeviceCommandsVo vo = iDeviceCommandsService.queryById(commandId);
        if(ObjectUtil.isEmpty(vo)){
            return  R.fail("参数有误，请核查！");
        }
        if(!StringUtils.equalsIgnoreCase(vo.getStatus(), DeviceCommandStatus.CREATE.getKey())){
            return R.fail("该命令已经下达，请核查！");
        }
        params.put("topic", StringUtils.format("/v1/devices/{}/command", vo.getDeviceIdentification()));
        params.put("message", vo.getCommandRequest());
        String result = mqttService.sendMessage(params);
        iDeviceCommandsService.updateStatusById(DeviceCommandStatus.WAIT.getKey(), vo.getId());
        return  R.ok(result);
    }
}
